package com.hl.godsent.utils

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.util.Log
import android.webkit.PermissionRequest
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.widget.ProgressBar
import android.widget.TextView
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import java.io.File
import kotlin.coroutines.coroutineContext


class CustomWebViewChrome(private val mActivity: Activity) : WebChromeClient() {
    private val uploadFile //定义接受返回值
            : ValueCallback<Uri>? = null
    private var uploadFiles: ValueCallback<Array<Uri>>? = null
    private val bar: ProgressBar? = null
    private val mTitle: TextView? = null
    override fun onProgressChanged(view: WebView, newProgress: Int) {
        super.onProgressChanged(view, newProgress)
    }

    override fun onReceivedTitle(view: WebView, title: String) {
        super.onReceivedTitle(view, title)
    }

    override fun onPermissionRequest(request: PermissionRequest) {
        request.grant(request.resources)
    }

    // For Android  >= 5.0
    override fun onShowFileChooser(
        webView: WebView,
        filePathCallback: ValueCallback<Array<Uri>>,
        fileChooserParams: FileChooserParams
    ): Boolean {
        uploadFiles = filePathCallback
        takePhoto()
        return true
    }

    /**
     * 唤起相机
     */
    private fun takePhoto() {
        var requestedOrientation =  mActivity.requestedOrientation
        PictureSelector.create(mActivity)
            .openCamera(SelectMimeType.ofImage())
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>) {
                    uploadFiles!!.onReceiveValue(arrayOf(Uri.parse(result[0].path)))
                    mActivity.requestedOrientation = requestedOrientation
                }
                override fun onCancel() {
                    Log.i("TAG", "取消啦")
                    uploadFiles!!.onReceiveValue(arrayOf(Uri.parse("")))
                    mActivity.requestedOrientation = requestedOrientation
                }
            })
    }

    /**
     * 选择相机
     */
    private fun openFileChooseProcess() {
        val i = Intent(Intent.ACTION_GET_CONTENT)
        i.addCategory(Intent.CATEGORY_OPENABLE)
        i.type = "image/*"
        mActivity.startActivityForResult(Intent.createChooser(i, "Choose"), CHOOSE_REQUEST_CODE)
    }

    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {}

    companion object {
        private const val CHOOSE_REQUEST_CODE = 1851074459
    }
}